#!/bin/bash
set -x

function try_lock() {
    if [ -f ./FILE_LOCK ];then
        echo "file locked"
        exit -1
    fi
    touch ./FILE_LOCK
}

function unlock() {
    if [ -f ./FILE_LOCK ];then
        rm ./FILE_LOCK
    fi
}

source ./config

cd ${dir}

tars=`ls | grep "tar$" | awk -F '.tar' '{print $1}'`

for t in ${tars}
do
    tar -xf ${t}.tar
    $hadoop_home/bin/hadoop fs -mkdir ${hdfs_dir}/${t}
    touch ${t}/app_data/PUTTING_LOCK
    $hadoop_home/bin/hadoop fs -put ${t}/app_data/PUTTING_LOCK ${hdfs_dir}/${t}/
    for tab in ${tables}
    do
         gunzip ${t}/app_data/${tab}.bson.gz
         $hadoop_home/bin/hadoop fs -put ${t}/app_data/${tab}.bson ${hdfs_dir}/${t}/
    done
    $hadoop_home/bin/hadoop fs -put ${t}/versions ${hdfs_dir}/${t}/
    $hadoop_home/bin/hadoop fs -rm ${hdfs_dir}/${t}/PUTTING_LOCK
    mv ${t}.tar ${t}.tar_bak
    rm -rf ${t}
    break
done

echo "done"
